# Copyright 2011-2011 by iNeed,Inc. All Rights Reserved.
#-*- encoding:utf-8 -*-
__author__  = "Number Huang<huang.bafeng@iNeed.com>"
__status__  = "developing"
__version__ = "0.1108.13.1"

import sys, os, time, string, message,database
from common import *
import sock_asyncore
import publishMatcher


class MsgCenter(object):
    """
    use case 1: init
            
  
    """

    def __init__(self,addr):

        self.log = getLogger("iNeed.Center",os.path.join(CENTER_LOG_PATH,"iNeedCenter.txt"))


        self.engineFactory = TaskEngineFactory(self)
        self.taskEngine    = self.engineFactory.getOneEngine("CenterTaskEngine",True)

        self.msgEngine  = self.engineFactory.getOneEngine("CenterMsgEngine")#msgEngine should be used independently to avoid the block
        self.msgProxy   = message.MsgProxy(self)
        self.msgEngine.addTask(self.msgProxy)
        self.listner    = self.msgProxy.createListner(addr)
        self.responseMap={
        #"NOTIFY":self.handleNotifyResponse,
        }

        self.requestMap={
        "NOTIFY":self.handleNotifyRequest,
        "PUBLISH":self.handlePublishRequest
        }
        self.notifyRequestMap={
                               CSTR_UDS: self._handleUpdateDriverStatus,
                               CSTR_BT: self._handleBTRequest,
                               CSTR_ET: self._handleETRequest,
                               CSTR_CM: self._handleCMRequest
                               }
        self.sessionID = centerFirstSession
        self.db    = database.CreateDB(self)
        self._cleanDriverStatus()
        self.matchingEngine = self.engineFactory.getOneEngine("matchingEngine",True)
        matchEngine = publishMatcher.getMatchEngine(self)
        self.matchingEngine.addTask(matchEngine)
        
    def exit(self):

        self.engineFactory.exit()
        self.msgProxy.exit()
        self.msgProxy.exit()

    def getMsgEngine(self):
        return self.msgEngine

    def getLocation(self):
        return (0,0,"iNeed Global Center")
    
    def getTaskEngine(self):
        return self.taskEngine

    def _cleanDriverStatus(self):
        """
        remove unactive drivers,
        currently the codition is the last time of updatestatus has past 900 seconds
        this could be a task combined with the checkAlive mechanism
        """
        condition={"time<":time.time()-900}
        self.db.delete("driverstatus",condition)
        #self.log.debug("")
    """
    handle request
    """
    def handleRequest(self,session,method,params):
        return self.requestMap[method](session,params)

    def handleNotifyRequest(self,session,params):
        action = params[0]
        return self.notifyRequestMap[action](session,params[1:])

    def _handleUpdateDriverStatus(self,session,params):

        
            driver       = session.getPeer()
            driver.updateDriverStatus(params[0],params[2])
            #update db
            locationDict = params[2]
            status       = params[0]["status"]
            locationDict["status"] = status
            
            database.updateLocation(self.db,EPR_DRIVER,locationDict)
            
    def _handleBTRequest(self,session,params):
        locationDict = params[2]
        paramsDict={}
        paramsDict["beginTime"]  = locationDict["Time"]
        paramsDict["status"]     = ESE_TRANSATION_GOING
        #score        = params[0]["score"]
        pubID        = params[0][CSTR2_PUBID]
        condition={"pubID=":pubID}
        self.db.update("order1",paramsDict,condition)
        
    def _handleETRequest(self,session,params):
        locationDict = params[2]
        paramsDict={}
        paramsDict["endTime"]    = locationDict["Time"]
        paramsDict["status"]     = EOS_CLOSED
     
        pubID                    = params[0][CSTR2_PUBID]
        condition={"pubID=":pubID}
        self.db.update("order1",paramsDict,condition)
        #session.sendStandyResponse("NOTIFY",params[3], EN_OK,retCodeMap[EN_OK])
    
    def _handleCMRequest(self,session,params):
        paramsDict={}
        paramsDict["score"]      = params[0]["score"]
        paramsDict["comment"]    = params[0]["comment"]
        pubID                    = params[0][CSTR2_PUBID]
        condition={"pubID=":pubID}
        self.db.update("order1",paramsDict,condition) 
          
    def handlePublishRequest(self,session,params):
        #matcher = PublishMatcher(session,params)
        #self.taskEngine.addTask(matcher,session)
        pass

    def getNextSessionID(self):
        self.sessionID += 1
        return self.sessionID
    
def Run():
     try:
        server = MsgCenter(centerAddr)
        exit = raw_input("exit?")
        server.exit()
     except:
        logging.exception("exit")
        
if __name__=="__main__":

    
   
    if False:
        import cProfile
        outProfileName="E:\kingCloud\ineed-taxi\code\doc\iNeedCenter.profile"
        cProfile.run('Run()', outProfileName)
    else:
        Run()